package com.chinairi.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinairi.common.utils.ResponseUtil;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.model.ReSeAddress;
import com.chinairi.mall.service.IReSeAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.chinairi.common.controller.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 收/发货地址表 前端控制器
 * </p>
 *
 * @author gsl
 * @since 2020-09-16
 */
@RestController
@RequestMapping("/re-se-address")
public class ReSeAddressController extends BaseController {

    @Autowired
    private IReSeAddressService iReSeAddressService;

    /**
     * 新增收货地址
     *
     * @param reSeAddress
     * @param request
     * @throws IOException
     */
    @PostMapping("/add")
    public void add(@RequestBody ReSeAddress reSeAddress, HttpServletRequest request) throws IOException {
        iReSeAddressService.add(reSeAddress,request);
        ResponseUtil.showMessage("success", "新增成功", "");
    }

    /**
     * 更新收货地址
     *
     * @param reSeAddress
     * @throws IOException
     */
    @PutMapping("/update")
    public void update(@RequestBody ReSeAddress reSeAddress) throws IOException {
        String rsaIsDefault = reSeAddress.getRsaIsDefault();
        //如果设置为默认地址，本用户其余的地址全部设为非默认
        if ("1".equals(rsaIsDefault)) {
            QueryWrapper<ReSeAddress> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("RSA_USER_CODE", UserSession.getUserId());
            List<ReSeAddress> reSeAddressList = iReSeAddressService.list(queryWrapper);
            for (ReSeAddress address : reSeAddressList) {
                address.setRsaIsDefault("0");
            }
            iReSeAddressService.saveOrUpdateBatch(reSeAddressList);
        }
        iReSeAddressService.updateById(reSeAddress);
        ResponseUtil.showMessage("success", "更新成功", "");
    }

    /**
     * 获取用户的收发货地址
     */
    @GetMapping("/get")
    public void get(HttpServletRequest request) throws IOException {
        List<ReSeAddress> reSeAddressList = iReSeAddressService.get(request);
        ResponseUtil.showMessage("success", "查询成功", reSeAddressList);
    }

    /**
     * 删除收发货地址
     *
     * @param rsaId
     * @throws IOException
     */
    @DeleteMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public void delete(String rsaId) throws IOException {
        iReSeAddressService.removeById(rsaId);
        ResponseUtil.showMessage("success", "删除成功", "");
    }


}
